<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}" class="medium-app-container">
    <!-- <MediumHeader type="back" /> -->
    <div v-loading="loading" class="main">
      <div class="order-list">
        <div class="order-item">
          <Title title="询单详情" font-size="16px" style="margin-bottom: 24px;" />
          <div class="order-detail-top">
            <!-- <ConsultOrderInfo v-if="orderData" :data="orderData" /> -->
            <MediumOrderItem
              :data="orderData"
              :is-show-btn="true"
              :select-num="selectNum"
              :select-total-user="selectTotalUser"
              :all-check="allCheck"
              :need-padding="false"
              @selectAll="selectAll"
              @setChecked="setChecked"
              @getSelectUser="getSelectUser"
              @submitOrder="toSubmitOrderModel"
              @getData="getOrder"
              @closeOrder="closeModel"
            />
          </div>
        </div>
        <div class="order-item">
          <!-- 非空 数组或对象 -->
          <div v-if="JSON.stringify(userListData) !== '{}'" class="user-list">
            <!-- 订单状态： 执行中 已完成 -->
            <div v-if="(Number(orderData.status) === 2 || Number(orderData.status) === 3) && hasRouteAuth('crm:orderList:add')" class="btn-right">
              <el-button
                type="primary"
                class="btn-operate btn-create"
                size="small"
                @click="toCreate">
                <div class="center">
                  <span class="name">批量生成订单</span>
                  <svg-icon icon-class="createOrder" style="width: 16px;height:16px"/>
                </div>
              </el-button>
            </div>
            <OrderUserList
              v-for="(i,key,index) in userListData"
              :ref="`userList${index}`"
              :key="key"
              :platform="key"
              :data="i"
              :order-status="Number(orderData.status)"
              style="padding-bottom: 32px;"
              @getOrder="getOrder"
              @getSelectUser="getSelectUser"
            />
          </div>
          <AddMedium v-if="(userAuthType === 1 || userAuthType === 3 )&& isShowAddMedium" :order-num="orderData.orderNum" @getOrder="getOrder" />

          <div v-if="JSON.stringify(recommendListData) !== '{}'" class="user-list">
            <div v-if="orderData.recommendList && orderData.recommendList.length && recommendListData" class="medium-icon"/>
            <OrderUserList
              v-for="(i,key,index) in recommendListData"
              :ref="`recommendList${index}`"
              :key="key"
              :platform="key"
              :data="i"
              :order-status="Number(orderData.status)"
              :user-list-type="'mediumRecommendList'"
              style="padding-bottom: 32px;"
              @getOrder="getOrder"
              @getSelectUser="getSelectUser"
            />
          </div>
          <AddMedium v-if="userAuthType === 2 && isShowAddMedium" :order-num="orderData.orderNum" @getOrder="getOrder" />
        </div>
        <div class="order-item">
          <div class="log-table">
            <Title title="操作日志" font-size="16px" style="margin-bottom: 24px;" />
            <div>
              <el-table
                v-if="logData.length"
                :data="logData"
                element-loading-text="加载中..."
                empty-text="暂无数据">
                <el-table-column align="left" label="操作类型">
                  <template slot-scope="scope">
                    <span>{{ scope.row.type || '--' }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="left" label="操作员">
                  <template slot-scope="scope">
                    <span>{{ scope.row.operator || '--' }}</span>
                  </template>
                </el-table-column>
                <!-- <el-table-column align="left" label="执行内容">
                  <template slot-scope="scope">
                    <span>{{ scope.row.content || '--' }}</span>
                  </template>
                </el-table-column> -->
                <el-table-column align="left" label="执行内容">
                  <template slot-scope="scope">
                    <div class="remarks-container">
                      <el-tooltip v-if="scope.row.content" :content="scope.row.content" class="item" placement="top" effect="dark">
                        <div class="remarks">{{ scope.row.content }}</div>
                      </el-tooltip>
                      <div v-else class="remarks">--</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column align="left" label="操作时间">
                  <template slot-scope="scope">
                    <span>{{ scope.row.time / 1000 | standardFormat('YYYY/MM/DD HH:mm') }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="left" label="备注" max-width="240">
                  <template slot-scope="scope">
                    <div class="remarks-container">
                      <el-tooltip v-if="scope.row.remark" :content="scope.row.remark" class="item" placement="top" effect="dark">
                        <div class="remarks">{{ scope.row.remark }}</div>
                      </el-tooltip>
                      <div v-else class="remarks">--</div>
                      <img v-if="userInfo.id === 1 || userInfo.id === scope.row.userId" :src="editRemark" class="edit-icon remark-icon" alt="" @click="toEditRemark(scope.row, scope.row.remark)">
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <empty-placeholder v-else style="margin-bottom: 24px" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <editMask ref="editInfoMask" input-type="textarea" @handelOk="handelEdit" />
  </div>
</template>
<script>
import { meidumOrderDetail, submitOrder, closeOrder, meidumOrderDetailLog, meidumOrderDetailLogEdit } from '@/api/medium';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import MediumOrderItem from '@/components/MediumPage/order/MediumOrderListItem';
import OrderUserList from '@/components/MediumPage/order/OrderUserList';
import AddMedium from '@/components/MediumPage/order/AddMedium';
import ConsultOrderInfo from '@/components/MediumPage/order/ConsultOrderInfo';
import editMask from '@/components/MediumPage/order/editPriceMask';
import Title from '@/components/Title';
import { standardFormatNoHour, standardFormat } from '@/filters/date';
import { formatPlatform } from '@/filters/medium';
import { hasRouteAuth } from '@/utils/permission';
import ElMessage from '@/utils/message';
import { TableData } from './mixin/mediumData';
import { mapState } from 'vuex';
import editRemark from '@/assets/medium/edit-remark.png';

export default {
  name: 'OrderDetail',
  components: { EmptyPlaceholder, MediumOrderItem, OrderUserList, AddMedium, ConsultOrderInfo, editMask, Title },
  filters: {
    standardFormatNoHour, standardFormat
  },
  data() {
    return {
      editRemark,
      id: '',
      orderData: {},
      selectUserSales: [],
      selectUserMedium: [],
      loading: false,
      userListData: {},
      recommendListData: {},
      selectNum: 0,
      allCheck: false,
      selectTotalUser: [],
      listTotal: 0,
      logData: [],
      batchOrderInfo: []
    };
  },
  computed: {
    ...mapState({
      'userAuthType': state => state.medium.userAuthType,
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isShowAddMedium() {
      // orderType 订单类型（1、泛询单，2、全向订单、3、定向订单）
      // status：待确认订单才能添加（1、待确认）
      return Number(this.orderData.status) === 1; // v2.1.4.1 放开订单类型限制
      // return Number(this.orderData.status) === 1 && this.orderData.orderType !== 3;
    }
  },
  created() {
    this.id = this.$route.params.id;
    this.getOrder();
    // console.log('用户', this.userInfo);
  },
  methods: {
    hasRouteAuth,
    async getOrder() {
      try {
        const params = {
          id: this.id
        };
        this.loading = true;
        const result = await meidumOrderDetail(params);
        this.loading = false;
        this.allCheck = false;
        this.orderData = result.data;
        // console.log(this.orderData);
        if (result.code === 200 && result.data) {
          // 媒介用户不显示待确认订单
          let userList = result.data.userList;
          const recommendList = result.data.recommendList;
          if (this.userAuthType === 2 && this.userInfo.userName !== '媒介管理员') {
            userList = userList.filter(i => i.status !== 1);
          }
          this.listTotal = Number(recommendList.length) + Number(userList.length);
          this.userListData = formatPlatform(userList);
          this.recommendListData = formatPlatform(recommendList);
          this.initSelect();
        }
        this.getOrderLog();
      } catch (error) {
        this.loading = false;
        console.log(error);
      }
    },
    async getOrderLog() {
      try {
        const params = {
          id: this.id
        };
        const result = await meidumOrderDetailLog(params);
        this.logData = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    selectAll(e) {
      const userListData = this.userListData;
      const recommendListData = this.recommendListData;
      for (let index = 0; index < Object.keys(userListData).length; index++) {
        if (this.$refs[`userList${index}`]) this.$refs[`userList${index}`][0].selectAll(e);
      }
      for (let index = 0; index < Object.keys(recommendListData).length; index++) {
        if (this.$refs[`recommendList${index}`]) this.$refs[`recommendList${index}`][0].selectAll(e);
      }
    },
    setChecked(type) {
      this.allCheck = type;
    },
    getSelectUser() {
      const userListData = this.userListData;
      const recommendListData = this.recommendListData;
      let result = [];
      for (let index = 0; index < Object.keys(userListData).length; index++) {
        const select = this.$refs[`userList${index}`][0].selectUserArray || [];
        result = result.concat(select);
      }
      for (let index = 0; index < Object.keys(recommendListData).length; index++) {
        const select = this.$refs[`recommendList${index}`][0].selectUserArray || [];
        result = result.concat(select);
      }

      this.selectNum = result.length;
      this.selectTotalUser = result;
      if (result.length >= this.listTotal) {
        this.allCheck = true;
      } else {
        this.allCheck = false;
      }
      this.batchOrderInfo = result;
      return result;
    },
    initSelect() {
      const userListData = this.userListData;
      const recommendListData = this.recommendListData;
      if (userListData) {
        for (let index = 0; index < Object.keys(userListData).length; index++) {
          if (this.$refs[`userList${index}`]) this.$refs[`userList${index}`][0].checkList = {};
        }
      }
      if (recommendListData) {
        for (let index = 0; index < Object.keys(recommendListData).length; index++) {
          if (this.$refs[`recommendList${index}`]) this.$refs[`recommendList${index}`][0].checkList = {};
        }
      }
    },
    toSubmitOrderModel() {
      const selectUser = this.getSelectUser();
      if (selectUser.length === 0) {
        this.$message({ type: 'warning', message: '请选择达人' });
        return;
      }
      this.$confirm('是否确定提交询单？', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        lockScroll: false,
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon',
        center: true
      }).then(() => {
        this.toSubmitOrder(selectUser);
      }).catch(() => {});
    },
    async toSubmitOrder(selectUser) {
      const orderData = this.orderData;
      if (selectUser.length === 0) {
        this.$message({ type: 'warning', message: '请选择达人' });
        return;
      }
      const params = {
        version: orderData.version,
        orderNum: orderData.orderNum,
        selectOptions: this.formatSelectUser(selectUser).selectOptions,
        unSelectOptions: this.formatSelectUser(selectUser).unSelectOptions
      };
      try {
        const res = await submitOrder(params);
        if (res.code === 200) {
          this.$message({ type: 'success', message: '提交成功' });
          this.getOrder();
        } else {
          this.$message({ type: 'error', message: res.message });
        }
      } catch (error) {
        console.log(error);
      }
    },
    formatSelectUser(selectUser) {
      const { userList = [], recommendList = [] } = this.orderData;
      const selectOptions = [];
      const unSelectOptions = [];
      const selectIds = [];
      const allUserList = userList.concat(recommendList);
      selectUser.forEach(i => {
        selectIds.push(i.id);
        selectOptions.push({
          version: i.version,
          id: i.id
        });
      });
      allUserList.forEach(i => {
        if (!selectIds.includes(i.id)) {
          unSelectOptions.push({
            version: i.version,
            id: i.id
          });
        }
      });
      return { selectOptions, unSelectOptions };
    },
    closeModel() {
      this.$confirm('确定关闭询单？', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        lockScroll: false,
        center: true,
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        this.toCloseOrder();
      }).catch(() => {});
    },
    async toCloseOrder() {
      const { userList = [], recommendList = [] } = this.orderData;
      const allUserList = userList.concat(recommendList);
      const options = [];
      allUserList.forEach(i => {
        options.push({
          version: i.version,
          id: i.id
        });
      });
      try {
        const params = {
          orderNum: this.orderData.orderNum,
          version: this.orderData.version,
          options
        };
        const res = await closeOrder(params);
        if (res.code === 200) {
          this.$message({ type: 'success', message: '关闭成功' });
          this.getOrder();
        } else {
          this.$message({ type: 'error', message: res.message });
        }
      } catch (error) {
        console.log(error);
      }
    },
    toCreate() {
      if (this.batchOrderInfo.length <= 0) {
        this.$message({ type: 'warning', message: '请选择资源' });
        return;
      }
      const data = {
        orderData: this.orderData,
        batchOrderInfo: this.formatBatchOrderInfo(this.batchOrderInfo)
      };
      localStorage.setItem('batchOrderInfo', JSON.stringify(data));
      this.$router.push({
        name: 'createOrderBatch',
        query: {
          model: 1, // 1：批量 0：单独
          consultId: this.$route.params.id
        }
      });
    },
    formatBatchOrderInfo(data) {
      try {
        const temp = [];
        data.forEach(item => {
          const arr = TableData[item.baseInfo.platformType || item.platformType].priceInfo;
          // console.log('pt', item, this.orderData);
          const obj = JSON.parse(JSON.stringify(item.priceInfo, this.removeNullsInObject));
          Object.keys(obj).forEach(e => {
            // console.log('price', arr.filter(list => list.key === e));
            const params = {
              priceType: arr.filter(list => list.key === e)[0].label,
              price: item.priceInfo[e],
              name: item.baseInfo.accountName,
              platformId: item.baseInfo.platformId || item.platformId,
              resourceId: item.baseInfo.resourceId,
              platformName: item.baseInfo.platform || item.platformTypeName,
              accountId: item.baseInfo.accountId
            };
            // articlesPrice terminalType theme
            // console.log('a', params);
            temp.push(params);
          });
        });
        return temp;
      } catch (error) {
        this.$message.warning('数据异常');
        return false;
      }
    },
    removeNullsInObject(key, value) {
      if (value === null || value === undefined) {
        return undefined;
      }
      return value;
    },
    toEditRemark(item, value) {
      this.inputType = 'textarea';
      this.$refs.editInfoMask.toEditRemarks(JSON.parse(JSON.stringify(item)), value, '备注');
    },
    async handelEdit({ data, key, value }) {
      // console.log('handelEdit', key);
      if (key === 'remark' && value.length > 500) {
        ElMessage.warning('请输入小于500个字的需求内容');
        return;
      }
      const params = {
        remark: value,
        id: data.id
      };
      try {
        const result = await meidumOrderDetailLogEdit(params);
        this.$refs.editInfoMask.init();
        if (result.code === 200) {
          this.getOrderLog();
        } else {
          this.$message({ type: 'error', message: result.message });
        }
      } catch (error) {
        this.$refs.editInfoMask.init();
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.medium-app-container {
  width: 100%;
  background-color: #f8fafb;
  padding-bottom: 50px;
  .main {
    width: 100%;
    padding: 0 24px;
    box-sizing: border-box;
    margin: 0 auto;
    background-color: #f8fafb;
    border-radius: 8px;
    padding-bottom: 20px;
  }
  .order-list {
    // box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
    // border-radius:12px;
    // overflow: hidden;
    margin-top: 24px;
    .order-item {
      background:rgba(255,255,255,1);
      box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
      border-radius:12px;
      width: 100%;
      overflow: hidden;
      padding: 24px 24px 0;
      // padding: 32px;
      margin-bottom: 24px;
    }
  }
  .medium-icon {
    background-color: #fff;
    &::before{
      width: 53px;
      display: block;
      content: '媒介';
      text-align: center;
      font-size: 12px;
      font-weight: 600;
      line-height: 21px;
      height: 21px;
      border-radius: 0px 10.5px 10.5px 0px;
      background-color: #55a7d2;
      color: #fff;
      margin-bottom: 10px;
    }
  }
  .remark-icon {
    margin-left: 5px;
    width: 16px;
    height: 16px;
    cursor: pointer;
    vertical-align: middle;
  }
  & ::v-deep {
    .el-table::before {
      border: none;
      height: 0;
    }
  }
}
.user-list {
  // padding-top: 30px;
}
.btn-right {
  text-align: right;
  padding-right: 32px;
}
.log-table {
  padding-bottom: 32px;
  & ::v-deep {
    .el-table__body {
      td {
        color: #666666;
      }
    }
  }
  .remarks-container {
    display: flex;
    align-items: center;
    text-align: left;
    &.center {
      justify-content: center;
    }
    .remarks {
      font-size: 14px;
      overflow:hidden;
      text-overflow:ellipsis;
      word-break:break-all;
      display:-webkit-box;
      -webkit-box-orient:vertical;
      line-clamp: 5;
      -webkit-line-clamp: 5;
    }
    .icon {
      margin-left: 5px;
      font-size: 13px;
      cursor: pointer;
      color: #55a7d2;
      &.larger {
        font-size: 16px;
      }
    }
  }
}
</style>
